package ui;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import model.CustomerGroup;
import model.Customer;
import service.CustomerService;
import service.AttributeService;
import utils.CommonUtil;
import utils.DBUtil;
import utils.ExcelExportUtil;
import utils.PdfUtil;

import java.util.ArrayList;
import java.util.List;

public class GroupDetailPage extends Application {

    private PdfUtil pdfUtil = new PdfUtil();
    private List<Customer> selectedCustomers = new ArrayList<>();
    private int groupId; // 用于获取分组内的客户
    private VBox vbox; // 用于存放客户的VBox
    private CheckBox selectAllCheckBox; // 全选复选框
    private CustomerService customerService = new CustomerService();

    // 构造方法，用于传递groupId
    public GroupDetailPage(int groupId) {
        this.groupId = groupId;
    }

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("分组详情页");

        vbox = new VBox();
        vbox.setPadding(new Insets(10));
        vbox.setSpacing(10);
        vbox.getStyleClass().add("root");

        // 滚动条
        ScrollPane scrollPane = new ScrollPane(vbox);
        scrollPane.setFitToWidth(true);
        scrollPane.getStyleClass().add("scroll-pane");

        // 全选按钮
        selectAllCheckBox = new CheckBox("全选");
        selectAllCheckBox.setOnAction(e -> selectAllCustomers(selectAllCheckBox.isSelected()));
        selectAllCheckBox.getStyleClass().add("select-all-checkbox");

        // 输出PDF按钮
        Button exportButton = new Button("导出pdf");
        exportButton.setPrefWidth(100);
        exportButton.setPrefHeight(40);
        exportButton.setOnAction(e -> {
            if (selectedCustomers.isEmpty()) {
                CommonUtil.showAlert("提示", "请先选择要导出的客户！", Alert.AlertType.WARNING);
                return;
            }
            pdfUtil.createCustomerPdfs(selectedCustomers); // 使用新的PDF导出方法
        });
        exportButton.getStyleClass().add("export-button");

        Button excelButton = new Button("导出excel");
        excelButton.setPrefWidth(150);
        excelButton.setPrefHeight(40);
        excelButton.setOnAction(e -> {
            if (selectedCustomers.isEmpty()) {
                CommonUtil.showAlert("提示", "请先选择要导出的客户！", Alert.AlertType.WARNING);
                return;
            }
            ExcelExportUtil.exportCustomersFromEAV(selectedCustomers); // 使用新的Excel导出方法
        });
        excelButton.getStyleClass().add("excel-button");

        // 删除按钮
        Button deleteButton = new Button("删除");
        deleteButton.setPrefWidth(100);
        deleteButton.setPrefHeight(40);
        deleteButton.setOnAction(e -> deleteSelectedCustomers());
        deleteButton.getStyleClass().add("delete-button");

        // 添加客户到分组按钮
        Button addCustomerButton = new Button("添加分组成员");
        addCustomerButton.setPrefWidth(140);
        addCustomerButton.setPrefHeight(40);
        addCustomerButton.setOnAction(e -> addCustomerToGroup());
        addCustomerButton.getStyleClass().add("add-button");

        // 返回按钮，返回到分组管理页面
        Button backButton = new Button("返回");
        backButton.setPrefWidth(100);
        backButton.setPrefHeight(40);
        backButton.setOnAction(e -> {
            GroupListPage currentPage = new GroupListPage();
            try {
                currentPage.start(new Stage());
                primaryStage.close();
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        });
        backButton.getStyleClass().add("back-button");

        // 创建一个HBox来对齐按钮
        HBox bottomButtons = new HBox(10);
        bottomButtons.setPadding(new Insets(10));

        // 左对齐全选复选框和其他按钮
        bottomButtons.getChildren().addAll(selectAllCheckBox, exportButton, deleteButton, addCustomerButton, backButton, excelButton);

        // 将按钮居中对齐
        bottomButtons.setAlignment(Pos.BOTTOM_LEFT);

        VBox root = new VBox(scrollPane, bottomButtons);
        root.setSpacing(10);
        root.getStyleClass().add("root");

        Scene scene = new Scene(root, 1000, 970);

        // 加载 CSS 样式
        scene.getStylesheets().add(getClass().getResource("/css/logisticsList.css").toExternalForm());

        primaryStage.setScene(scene);
        primaryStage.show();

        // 初次加载分组客户
        loadGroupDetailsPage();
    }

    /**
     * 加载并刷新分组客户详情页
     */
    private void loadGroupDetailsPage() {
        // 清空之前显示的内容
        vbox.getChildren().clear();
        selectedCustomers.clear();

        // 获取特定分组的客户数据
        List<Customer> customers = DBUtil.selectCustomersByGroupId(groupId);

        for (Customer customer : customers) {
            HBox row = new HBox();
            row.setSpacing(10);
            row.getStyleClass().add("hbox");

            // 左侧复选框
            CheckBox checkBox = new CheckBox();
            checkBox.selectedProperty().addListener((observable, oldValue, newValue) -> {
                if (newValue) {
                    selectedCustomers.add(customer);
                } else {
                    selectedCustomers.remove(customer);
                }
            });
            checkBox.getStyleClass().add("check-box");

            // 中间显示客户名称
            Label nameLabel = new Label(customer.getCustomerName());
            HBox.setHgrow(nameLabel, Priority.ALWAYS);
            nameLabel.setMaxWidth(Double.MAX_VALUE);
            nameLabel.getStyleClass().add("label");

//            // 右侧"详情"按钮
//            Button detailButton = new Button("详情");
//            detailButton.setOnAction(e -> {
//                CustomerDetailPage detailPage = new CustomerDetailPage(customer);
//                try {
//                    detailPage.start(new Stage());
//                    ((Stage) detailButton.getScene().getWindow()).close();
//                } catch (Exception ex) {
//                    ex.printStackTrace();
//                }
//            });
//            detailButton.getStyleClass().add("button");

            row.getChildren().addAll(checkBox, nameLabel);
            vbox.getChildren().add(row);
        }
    }

    /**
     * 全选或取消全选客户
     */
    private void selectAllCustomers(boolean select) {
        // 先清空已选择的客户列表
        selectedCustomers.clear();
        
        // 设置所有复选框的选中状态
        for (javafx.scene.Node node : vbox.getChildren()) {
            if (node instanceof HBox) {
                HBox row = (HBox) node;
                for (javafx.scene.Node innerNode : row.getChildren()) {
                    if (innerNode instanceof CheckBox) {
                        CheckBox checkBox = (CheckBox) innerNode;
                        checkBox.setSelected(select);
                    }
                }
            }
        }
        
        // 如果是全选，则重新获取所有客户并添加到selectedCustomers
        if (select) {
            List<Customer> customers = DBUtil.selectCustomersByGroupId(groupId);
            selectedCustomers.addAll(customers);
        }
    }

    /**
     * 删除选中的客户信息
     */
    private void deleteSelectedCustomers() {
        if (selectedCustomers.isEmpty()) {
            showAlert("提示", "未选择任何客户进行删除。", Alert.AlertType.INFORMATION);
            return;
        }

        // 遍历选中的客户列表并删除
        for (Customer customer : selectedCustomers) {
            customerService.deleteCustomer(customer.getCustomerId()); // 使用CustomerService删除客户
        }

        // 删除完毕后清空选中的客户列表
        selectedCustomers.clear();

        // 重新加载页面以刷新客户列表
        loadGroupDetailsPage();
    }

    /**
     * 添加客户到分组
     */
    private void addCustomerToGroup() {
        // 新建一个窗口用于显示客户选择界面
        Stage addCustomerStage = new Stage();
        addCustomerStage.setTitle("选择客户并添加到分组");

        VBox vbox = new VBox(10);
        vbox.setPadding(new Insets(10));

        // 获取当前分组内已经存在的客户列表
        List<Customer> existingCustomers = DBUtil.selectCustomersByGroupId(groupId);

        // 获取所有客户列表
        List<Customer> allCustomers = customerService.getAllCustomers();
        List<Customer> selectedCustomers = new ArrayList<>();
        VBox customerListBox = new VBox(10);

        // 过滤掉已经在当前分组中的客户
        for (Customer customer : allCustomers) {
            if (existingCustomers.stream().anyMatch(existing -> existing.getCustomerId() == customer.getCustomerId())) {
                continue;
            }

            HBox customerRow = new HBox(10);
            CheckBox checkBox = new CheckBox(customer.getCustomerName());

            checkBox.selectedProperty().addListener((observable, oldValue, newValue) -> {
                if (newValue) {
                    selectedCustomers.add(customer);
                } else {
                    selectedCustomers.remove(customer);
                }
            });

            customerRow.getChildren().add(checkBox);
            customerListBox.getChildren().add(customerRow);
        }

        ScrollPane scrollPane = new ScrollPane(customerListBox);
        scrollPane.setFitToWidth(true);

        Button confirmButton = new Button("添加选中客户");
        confirmButton.setOnAction(e -> {
            if (selectedCustomers.isEmpty()) {
                showAlert("提示", "请选择至少一个客户进行添加。", Alert.AlertType.INFORMATION);
            } else {
                for (Customer customer : selectedCustomers) {
                    CustomerGroup customerGroup = new CustomerGroup(customer.getCustomerId(), groupId);
                    DBUtil.insertCustomerGroup(customerGroup);
                }

                addCustomerStage.close();
                loadGroupDetailsPage(); // 刷新分组客户列表
            }
        });

        vbox.getChildren().addAll(scrollPane, confirmButton);

        Scene scene = new Scene(vbox, 400, 300);
        addCustomerStage.setScene(scene);
        addCustomerStage.show();
    }

    /**
     * 显示提示信息对话框
     */
    private void showAlert(String title, String message, Alert.AlertType alertType) {
        Alert alert = new Alert(alertType);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }
}
